﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Write.Api.Application.Command.Product;

namespace Provenance.Write.Api.Application.CommandHandler.Product
{
    public class DelRangeProductInfoCommandHandler : IRequestHandler<DelRangeProductInfoCommand, ApiResult>
    {
        private readonly IProductInfoRepository _productInfoRepository;
        private readonly ILogger<DelRangeProductInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public DelRangeProductInfoCommandHandler(IProductInfoRepository productInfoRepository, ILogger<DelRangeProductInfoCommandHandler> logger, IMapper mapper)
        {
            _productInfoRepository = productInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(DelRangeProductInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                int[]Ids=request.ProductInfoIds.Split(',').Select(x=>int.Parse(x)).ToArray();
                var list = await _productInfoRepository.GetAllAsync(x => Ids.Contains(x.ProductInfoId) && x.IsDeleted == false);
                if (list.Count == 0)
                {
                    return ApiResult.Failure("No product found to delete.");
                }
                foreach(var item in list)
                {
                    item.IsDeleted = true;
                }
                await _productInfoRepository.DeleteRangeEntity(list);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error deleting productList info:" + ex.Message);
                return ApiResult.Failure("Error deleting productList info:" + ex.Message);
            }
        }
    }
}
